package com.ht.module.bus.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.abnormal.HtException;
import com.ht.constant.BusConstant;
import com.ht.constant.DicConstants;
import com.ht.module.bus.entity.TClass;
import com.ht.module.bus.entity.TDistrict;
import com.ht.module.bus.entity.TStudentTripStatistics;
import com.ht.module.bus.mapper.TStudentTripStatisticsMapper;
import com.ht.module.bus.service.TClassService;
import com.ht.module.bus.service.TDistrictService;
import com.ht.module.bus.service.TStudentTripStatisticsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.util.CommMethod;
import com.ht.util.Pager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生出行统计信息填报表 服务实现类
 * </p>
 *
 * @author hejialun
 * @since 2024-08-20
 */
@Service
public class TStudentTripStatisticsServiceImpl extends ServiceImpl<TStudentTripStatisticsMapper, TStudentTripStatistics> implements TStudentTripStatisticsService {
    @Resource
    private TDistrictService districtService;
    @Resource
    private TClassService classService;

    @Override
    public Pager<TStudentTripStatistics> findPage(Pager<TStudentTripStatistics> pager, TStudentTripStatistics en) {
        baseMapper.findPageAuth(pager, getQW(en), null);
        handleDistrictCode(pager.getRecords());
        return pager;
    }


    /**
     * 处理区划
     *
     * @param records
     */
    private void handleDistrictCode(List<TStudentTripStatistics> records) {
        //查询出所有区划
        List<TDistrict> districts = districtService.findAll();
        //查询出所有班级
        List<TClass> classes = classService.findList(new TClass());

        for (TStudentTripStatistics record : records) {
            //设置班级年级
            TClass tClass = classes.stream().filter(x -> StrUtil.equals(x.getClassCode(), record.getClassCode())).findFirst().orElse(null);
            if (tClass != null) {
                record.setGrade(tClass.getGrade());
            }
            //设置当前学校所属区划名称
            TDistrict schoolDistrict = districts
                    .stream()
                    .filter(x -> StrUtil.equals(x.getDistrictCode(), record.getSchoolDistrictCode()))
                    .findFirst().orElse(null);
            if(schoolDistrict!=null){
                record.setSchoolDistrictName(schoolDistrict.getDistrictName());
            }
            //设置常驻区划
            TDistrict districtCode = districts
                    .stream()
                    .filter(x -> StrUtil.equals(x.getDistrictCode(), record.getDistrictCode()))
                    .findFirst().orElse(null);
            if (districtCode == null) {
                continue;
            }
            //判断常驻区划属于街道还是社区-如果属于社区，查询出他对应的街道区划
            if (StrUtil.equals(districtCode.getDistrictLevel(), "5")) {
                //社区-查询出对应的街道-上级
                TDistrict pDistrictCode = districts
                        .stream()
                        .filter(x -> StrUtil.equals(x.getDistrictCode(), districtCode.getParentDistrictCode()))
                        .findFirst().orElse(null);
                if (pDistrictCode == null) {
                    continue;
                }
                //设置社区数据
                record.setCommunityDistrictCode(districtCode.getDistrictCode());
                record.setCommunityDistrictName(districtCode.getDistrictName());
                //设置街道数据
                record.setStreetDistrictCode(pDistrictCode.getDistrictCode());
                record.setStreetDistrictName(pDistrictCode.getDistrictName());
            } else if (StrUtil.equals(districtCode.getDistrictLevel(), "4")) {
                //设置街道数据
                record.setStreetDistrictCode(districtCode.getDistrictCode());
                record.setStreetDistrictName(districtCode.getDistrictName());
            }
        }
    }


    private QueryWrapper<TStudentTripStatistics> getQW(TStudentTripStatistics en) {
        QueryWrapper<TStudentTripStatistics> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(en.getDistrictCode())) {
            qw.eq("district_code", en.getDistrictCode());
        }

        if (StrUtil.isNotEmpty(en.getClassCode())) {
            qw.eq("class_code", en.getClassCode());
        }

        if (StrUtil.isNotEmpty(en.getClassName())) {
            qw.like("class_name", en.getClassName());
        }

        if (StrUtil.isNotEmpty(en.getSchoolCode())) {
            qw.eq("school_code", en.getSchoolCode());
        }
        if (StrUtil.isNotEmpty(en.getSchoolName())) {
            qw.like("school_name", en.getSchoolName());
        }
        if (StrUtil.isNotEmpty(en.getGradeCode())) {
            //分隔年级
            String[] split = en.getGradeCode().split(",");
            if (split.length > 1) {
                //分隔成字符串
                qw.eq("school_code", split[0]);
                //获取字符串中的一二三四
                Pattern pattern = Pattern.compile("[零一二三四五六七八九]");
                Matcher matcher = pattern.matcher(split[1]);

                // 用于保存提取出的中文数字
                StringBuilder extractedDigits = new StringBuilder();
                // 提取匹配的中文数字
                while (matcher.find()) {
                    extractedDigits.append(matcher.group());
                }
                //获取层级年级
                if(en.getGradeCode().contains("幼")){
                    qw.eq("education_stage", DicConstants.EducationStage.YEY);
                }

                if(en.getGradeCode().contains("年级")){
                    qw.eq("education_stage",DicConstants.EducationStage.XX);
                }


                if(en.getGradeCode().contains("初")){
                    qw.eq("education_stage",DicConstants.EducationStage.CZ);
                }

                if(en.getGradeCode().contains("高")){
                    qw.eq("education_stage",DicConstants.EducationStage.GZ);
                }
                //获取年级数字
                qw.eq("grade_number",CommMethod.convertChineseToArabic(extractedDigits.toString()));
            }
        }

        if (StrUtil.isNotEmpty(en.getState())) {
            qw.eq("state", en.getState());
        }
        qw.eq("del_flag", BusConstant.DEL_FLAG_N);
        return qw;
    }

    @Override
    public void add(TStudentTripStatistics en) {
        //判断当前数据是否存在
        Integer i = baseMapper.selectCount(
                new QueryWrapper<TStudentTripStatistics>()
                        .eq("class_code", en.getClassCode())
                        .eq("district_code", en.getDistrictCode())
        );
        if (i > 0) {
            throw new HtException("当前班级，常驻区划下的数据已经存在！");
        }
        baseMapper.insert(en);

    }

    @Override
    public void editById(TStudentTripStatistics en) {
        //判断当前数据是否存在
        Integer i = baseMapper.selectCount(
                new QueryWrapper<TStudentTripStatistics>()
                        .eq("class_code", en.getClassCode())
                        .eq("district_code", en.getDistrictCode())
                        .ne("trip_code", en.getTripCode())
        );
        if (i > 0) {
            throw new HtException("当前班级，常驻区划下的数据已经存在！");
        }
        baseMapper.updateById(en);
    }

    @Override
    public Integer addList(List<TStudentTripStatistics> list) {
        List<TStudentTripStatistics> saveList = new ArrayList<>();

        for (TStudentTripStatistics en : list) {
            Integer i = baseMapper.selectCount(
                    new QueryWrapper<TStudentTripStatistics>()
                            .eq("class_code", en.getClassCode())
                            .eq("district_code", en.getDistrictCode())

            );
            //判断当前数据集里面是否有重复的
            long count = saveList.stream().filter(x ->
                    StrUtil.equals(x.getClassCode(), en.getClassCode())
                            && StrUtil.equals(x.getDistrictCode(), en.getDistrictCode())
            ).count();

            if (i == 0 && count == 0) {
                CommMethod.beanCreate(en);
                saveList.add(en);
            }
        }
        this.saveBatch(saveList);
        return saveList.size();
    }
}
